﻿using NewLife.Reflection;
using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Linq;
using System.Net.WebSockets;
using System.Text;
using System.Threading;
using System.Threading.Tasks;

namespace GXRTBTC.PublicClassLibrary.Model
{
    /// <summary>
    /// WebsocketClientManager
    /// </summary>
    public static class WebsocketClientManager
    {
        /// <summary>
        /// Websocket管理类
        /// </summary>
        public static WebsocketClientCollection websocketClient { get; set; } = new WebsocketClientCollection();
    }

    /// <summary>
    /// Websocket管理类
    /// </summary>
    public class WebsocketClientCollection
    {
        /// <summary>
        /// 所有连接
        /// </summary>
        public List<WebsocketClient> _clients = new();
        /// <summary>
        /// 添加连接
        /// </summary>
        /// <param name="client"></param>
        public void Add(WebsocketClient client)
        {
            var tmpClient = GetByPositionId(client.positionId);
            if (tmpClient != null)
            {
                _clients.Remove(tmpClient);
            }
            _clients.Add(client);
        }
        /// <summary>
        /// 移除连接
        /// </summary>
        /// <param name="client"></param>
        public void Remove(WebsocketClient client)
        {
            _clients.Remove(client);
        }
        /// <summary>
        /// 根据ID获取连接
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        public WebsocketClient Get(string id)
        {
            return _clients.FirstOrDefault(c => c.id == id);
        }
        /// <summary>
        /// 根据ID设置工位号
        /// </summary>
        /// <param name="id"></param>
        /// <param name="positionId"></param>
        public WebsocketClient GetByPositionId(string positionId)
        {
            return _clients.FirstOrDefault(c => c.positionId == positionId);
        }
        /// <summary>
        /// 根据ID设置最新心跳时间
        /// </summary>
        /// <param name="id"></param>
        public void SetTime(string id)
        {
            var client = Get(id);
            if (client != null)
            {
                client.newTime = DateTime.Now;
            }
        }
        /// <summary>
        /// 根据client设置最新心跳时间
        /// </summary>
        /// <param name="client"></param>
        public void SetTime(WebsocketClient client)
        {
            SetTime(client.id);
        }
        /// <summary>
        /// 根据ID设置鉴权标志
        /// </summary>
        /// <param name="id"></param>
        /// <param name="auth"></param>
        public void SetAuth(string id, bool auth)
        {
            var client = Get(id);
            if (client != null)
            {
                client.auth = auth;
            }
        }
        /// <summary>
        /// 根据client设置鉴权标志
        /// </summary>
        /// <param name="client"></param>
        /// <param name="auth"></param>
        public void SetAuth(WebsocketClient client, bool auth)
        {
            SetAuth(client.id, auth);
        }
        /// <summary>
        /// 获取鉴权
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        public bool GetAuth(string id)
        {
            var client = Get(id);
            if (client != null)
            {
                return client.auth;
            }
            return false;
        }
        /// <summary>
        /// 获取鉴权
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        public bool GetAuth(WebsocketClient client)
        {
            return GetAuth(client.id);
        }
        /// <summary>
        /// 获取连接数量
        /// </summary>
        /// <returns></returns>
        public int GetCount()
        {
            return _clients.Count;
        }
        /// <summary>
        /// 获取连接
        /// </summary>
        /// <returns></returns>
        public List<WebsocketClient> Getlist()
        {
            return _clients;
        }
        public WebsocketClientCollection()
        { 
            new Thread(ClearUnUseConn).Start();
        }
        /// <summary>
        /// 定时移除无效连接
        /// </summary>
        public void ClearUnUseConn()
        {
            while (true)
            {
                try
                {
                    List<WebsocketClient> tmpClients = new();
                    foreach (var client in _clients)
                    {
                        if (client.webSocket.State != WebSocketState.Open && client.webSocket.State != WebSocketState.Connecting)
                        {
                            tmpClients.Add(client);
                        }
                    }
                    if (tmpClients.Count > 0)
                    {
                        foreach (var client in tmpClients)
                        {
                            _clients.Remove(client);
                        }
                    }
                }
                catch { }
                finally
                { 
                    Thread.Sleep(60 * 1000);
                }
            }
        }
    }

    /// <summary>
    /// 连接类
    /// </summary>
    public class WebsocketClient
    {
        /// <summary>
        /// HttpContext连接ID
        /// </summary>
        public string id { get; set; } = "";
        /// <summary>
        /// 工位号，下发定位用
        /// </summary>
        public string positionId { get; set; } = "";
        /// <summary>
        /// WebSocket对象
        /// </summary>
        public WebSocket webSocket { get; set; }
        /// <summary>
        /// 是否已经鉴权
        /// 目前默认都不用鉴权
        /// </summary>
        public bool auth { get; set; } = true;
        /// <summary>
        /// 连接时间
        /// </summary>
        public DateTime getTime { get; set; } = DateTime.Now;
        /// <summary>
        /// 最新心跳时间
        /// </summary>
        public DateTime newTime { get; set; } = DateTime.Now;
    }
}